import { Body, Controller, Post } from '@midwayjs/core';
import axios from 'axios';
import * as cheerio from 'cheerio';
import puppeteer, { executablePath } from 'puppeteer-core';

@Controller('/')
export class HomeController {
  @Post('/')
  async home(@Body() body: any): Promise<any> {
    try {
      const html = cheerio.load(`<a href="https://tinify.com/login?token=rZ9G8PVqGjBlZtmmfdD7f45Kmnr194sk/xXyhPzvgdqpq244&amp;new=true&amp;redirect=/dashboard/api" style="background: #3abbd0; border-color: #3abbd0; border-radius: 2px; border-style: solid; border-width: 15px 15px 13px 20px; box-shadow: 0px 4px 0px 0px #269eb1; color: white; display: inline-block; font-family: Arial, sans-serif; font-size: 16px; font-weight: bold; letter-spacing: 0.03em; line-height: 17px; margin: 10px auto 15px; text-align: center; text-decoration: none; text-shadow: 1px 1px 1px #269eb1">Visit your dashboard</a>`, null, false)
      console.log("===323===", html('a').attr('href'));
      const src = html('a').attr('href');
      const browser = await puppeteer.launch({
        headless: true,
        ignoreHTTPSErrors: true,
        // add this
        executablePath: executablePath("chrome")
      });
      const page = await browser.newPage();
      await page.goto(src)
      await page.setViewport({ width: 1080, height: 1024 });
      // await page.setDefaultTimeout(5*1000)
      await page.waitForSelector('section .usage')
      await page.waitForTimeout(1000);

      const session = await page.evaluate(async () => {
        return Promise.resolve(await localStorage.getItem('tinify-session'));
      })
      const token = JSON.parse(session).token;
      const res = await axios.get('https://api.tinify.com/api', {
        headers: {
          "Authorization": `Bearer ${token}`
        }
      })
      const keyObj = res.data['keys'][0] as {
        "identifier": null,
        "key": string,
        "state": string,
        "raw_units": string
      };
      if (keyObj.state != "active") {
        const res1 = await axios.patch(`https://api.tinify.com/api/keys/${keyObj.key}`, {
          state: "active"
        }, { headers: { "Authorization": `Bearer ${token}` } })
        console.log("=====", res1.data)
      }
      return { ...res.data }

    } catch (error) {
      console.log("====", error);

    }

    return ""
  }
  @Post('/create')
  async createAccount(@Body('fullName') fullName: string, @Body('mail') mail: string) {
    try {
      const res = await axios.post('https://tinypng.com/web/api', { fullName, mail })
      return { ...res.data }
    } catch (error) {
      return { ...error }
    }


  }
}

